package com.hframe.http.client;


import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;

/**
 * Created by heqian on 12/6/16.
 */

public abstract class FileSuccess implements Success {
    protected String savePath = null;
    protected String fileName = null;
    protected FileOutputStream output = null;
    protected HttpClients client = null;

    public abstract void onFinish(String path);

    public FileSuccess(String savePath) {
        this.savePath = savePath;
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public FileSuccess(String savePath, String fileName) {
        this.savePath = savePath;
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        this.fileName = fileName;
    }

    @Override
    public void setHttpClient(HttpClients client) {
        this.client = client;
    }

    @Override
    public void start(HttpURLConnection connection) throws Exception {
        if (null == fileName) {
            fileName = connection.getHeaderField("Content-disposition");
            if (null != fileName)
                fileName = fileName.substring(fileName.indexOf("filename=") + 10, fileName.length() - 1);
        }

        if (null == fileName) {
            String url = client.getUri().getPath();
            int index = url.lastIndexOf("/");
            if (0 <= index && index < url.length() - 1)
                fileName = url.substring(index + 1);
        }

        if (!"/".equals(savePath.substring(savePath.length() - 1)))
            savePath += "/";

        if (null != fileName)
            this.output = new FileOutputStream(new File(savePath + fileName));
    }


    @Override
    public void finish(HttpURLConnection connection) throws Exception {
        if (null != this.output)
            output.close();

        onFinish(savePath + fileName);
    }

    @Override
    public boolean onDownload(Progress.DataItem data, HttpURLConnection connection) throws Exception {
        if (null != this.output)
            this.output.write(data.data);
        return true;
    }
}
